-- NewBagRender 对Res.NewBagNode的解析

local ClassRef = app.mvc.createRenderClass(...)

local jewelNum = 4
local SLOT_GAP = 12
local crystalNum = 6

local gemDistanceOfX = 0 -- 宝石孔X间距
local gemMiddlePosX = 0 -- 宝石孔居中X坐标
local crystalDistanceOfX = 0
-- data = Item/Equip
function ClassRef.create(node, isMultipleLayerNode)
	if not node then
		node = display.createMultipleLayerRenderWithCsbPath(Res.NewBagNode, isMultipleLayerNode)
	end
	local sprite = ClassRef.extend(node)
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	display.setCascadeColorEnabled( self, true )

	self._tipEnable = false
	self._isTouchTip = false
	-- self._bgBtn = self._ui["bg"]

	-- self:setContentSize(self._bgBtn:getContentSize())

	self:setSelected(false)
	display.uiAddClick( self, function(sender, eventType)
		self:handleClick()
	end )

	-- 以下：根据策划要求，背包中物品不显示强化等级相关
	self._ui["img_ContinueFlag"]:setVisible( false )
	self._ui["num"]:setVisible(false)

	gemDistanceOfX = self._ui["Panel_gem/gem_2"]:getPositionX() - self._ui["Panel_gem/gem_1"]:getPositionX()
	crystalDistanceOfX = self._ui["Panel_wing/gem_2"]:getPositionX() - self._ui["Panel_wing/gem_1"]:getPositionX()
	gemMiddlePosX = self._ui["Panel_gem"]:getContentSize().width/2

	-- self:refresh()
end

function ClassRef:handleClick()
	-- 清理isNew
	if self._data and self._data.isNew then
	    self._data:setIsNewGet(false)
	    self:setIsNew(false)
	    UD.redPoint:checkStateByKey(RedPointConstant.Bag_NewItem)
	end

	if self._isTouchTip then
		self:setSelected(false)
	else
		-- 修改当前选中
		local isSelected = not self:isSelected()
		self:setSelected(isSelected)
		if self._model then
			self._model:dispatchEvent("click", self)
		end
		if isSelected then
			self:showTip()
		end
	end
end

-- function ClassRef:getRenderData()
-- 	if not self._data then
-- 		return 
-- 	end
-- 	return self._data.renderData
-- end

function ClassRef:setNewScale(len)
	self:setAnchorPoint(cc.p(0.5,0.5))
	local size = self:getContentSize()
	local scale = len / size.height
	self:setScale(scale)
end

function ClassRef:refreshState()
	if self._model then
		self:setSelected(self._model:getUIState("selected") == true)
		self:setMask(self._model:getUIState("mask") == true)
	end
end

function ClassRef:refresh()
	local renderData = self._data
	self:setClickEnable(renderData ~= nil)
	self:refreshState()
	if renderData then
		self:setIsNew(renderData.isNew)
		self:setIcon(renderData:getIcon())
		self:setNum(renderData.amount or 1)
		self:setIconKuang(renderData:getIconBg())

		if renderData.itemBagType == Enums.ItemBagType.jewel then
			self:setIsOther( false )
			self:setIsBind( true )
		else
			self:setIsOther(not renderData:isClassEnable())
			self:setIsBind(renderData:isBind())
		end

		if renderData.itemBagType == Enums.ItemBagType.equip then -- 装备？
			self:showGemSlots(renderData:getAllSlots())
			self:showRockSlots(renderData:getAllCrystalSlots(), renderData:getRockNum())
			self:setTransferred( renderData:canTransAttr() )
			self:setStrengthen( renderData:isBetterThanEquipOnPlayer() )
			self:setStrengthenedLv()

			self:setContinueStrengthen( false )
		elseif renderData.itemBagType == Enums.ItemBagType.jewel then -- 珠宝？
			self:showGemSlots({})
			self:showRockSlots(0,0)
			self:setTransferred(false)
			self:setStrengthen(false)
			self:setNum()
--			self:setStrengthenedLv( renderData:getLevel() )
            -- 客户端将宝石等级主动+1
			self:setStrengthenedLvEx(renderData:getLevelPlus1())
		else
			self:showGemSlots({})
			self:showRockSlots(0,0)
			self:setTransferred(false)
			self:setStrengthen(false)
			self:setContinueStrengthen( false )

			if self._data:getItemType() == Enums.ItemType.crystal then
				local rockInfo = GD:queryRockById(self._data:getId())
				self:setStrengthenedLvEx(tonumber(rockInfo.leve))
			elseif self._data:getItemType() == Enums.ItemType.transattr then -- 属性条卷轴
				self:setTransferred(renderData:canTransAttr())
				self:setStrengthenedLvEx()
			elseif self._data:getItemType() == Enums.ItemType.allAttrScroll then -- 万能属性条卷轴
				self:setTransferred(renderData:allAttrScrollCanTransAttr())
				self:setStrengthenedLvEx()
			else
				self:setStrengthenedLvEx()
			end
		end
	else -- 无数据
		self:setIsNew(false)
		self:setIcon(nil)
		self:setNum(nil)
		self:setIconKuang(nil)
		self:setIsOther(false)
		self:setIsBind(false)
		self:showRockSlots(0,0)

		self:setTransferred(false)
		self:setStrengthen(false)
		self:setContinueStrengthen( false )
		self:setStrengthenedLv()

		self._ui["Panel_gem"]:setVisible(false)
	end
end

function ClassRef:showGemSlots(slots)
	self._ui["Panel_gem"]:setVisible(#slots > 0)
	if #slots > 0 then
		local midX = self._ui["Panel_gem"]:getContentSize().width/2
		local startX = midX - (#slots - 1) / 2 * SLOT_GAP
		local showGems = {}
		local gemVisibleNum = 0 -- 宝石孔可见数量
		for i=1,jewelNum do
			local slot = slots[i]
			local gem = self._ui["Panel_gem"]:getChildByName( "gem_"..i )
			gem:setVisible(slot ~= nil)
			table.insert(showGems,gem)
			if slot then
				gemVisibleNum = gemVisibleNum + 1
				gem:getChildByName("bg"):loadTexture( GD:getImagePath( Res.slotIconPath, "common_cell_gem1" ) )
				if slot:hasJewel() then
					gem:getChildByName("gem"):setVisible( true )
					gem:getChildByName("gem"):loadTexture( slot.jewel:getMiniIcon() )
				else
					-- gem:getChildByName("bg"):loadTexture( GD:getImagePath( Res.slotIconPath, "common_cell_gem1" ) )
					gem:getChildByName("gem"):setVisible( false )
				end
			end
		end
		-- 以下：做宝石孔的动态位置调整
		display.autoAdjustNodesPosX( self._ui["Panel_gem"]:getContentSize().width, showGems, gemVisibleNum, gemDistanceOfX)
	end
end





function ClassRef:showRockSlots(crystalIds,rockNum)
	self._ui["Panel_wing"]:setVisible(rockNum > 0)
	if rockNum > 0 then
		local gemVisibleNum = rockNum -- 水晶孔可见数量
		local showGems = {}
		for i=1,crystalNum do
			local rockId = crystalIds[i]
			local gem = self._ui["Panel_wing/gem_" .. i]
			table.insert(showGems,gem)
			gem:setVisible(rockNum >= i)
			if rockId then
				local rockInfo = GD:queryRockById(tonumber(rockId))
				if rockInfo then
					gem:getChildByName("wing"):setVisible( true )
					gem:getChildByName("wing"):loadTexture( GD:getImagePath(Res.slotIconPath, "common_cell_crystal"..tostring(rockInfo.type)))
				end
			else
				gem:getChildByName("wing"):setVisible( false )
			end
		end

		display.autoAdjustNodesPosX( self._ui["Panel_wing"]:getContentSize().width, showGems, gemVisibleNum, wingGemDistanceOfX)
	end
end

function ClassRef:setIconKuang(res)
	if res then
		self._ui["grade"]:setVisible(true)
		self._ui["grade"]:loadTexture(res)
	else
		self._ui["grade"]:setVisible(false)
	end
end

function ClassRef:setImgKuang(res)
end

function ClassRef:setIcon(res)
	if res then
		self._ui["icon"]:setVisible(true)
		self._ui["icon"]:loadTexture(res)
	else
		self._ui["icon"]:setVisible(false)
	end
end

function ClassRef:setNum(num)
	if num then
		local str = num > 1 and tostring(num) or ""
		self._ui["Panel_num"]:setVisible(num > 1)
		self._ui["Panel_num/num"]:setString(str)
	else
		self._ui["Panel_num"]:setVisible(false)
	end
end

function ClassRef:setIsNew(b)
	self._ui["dot"]:setVisible(b)
end

function ClassRef:setIsEquip(b)
	-- self._ui.icon_e:setVisible(b)
end

function ClassRef:setIsBind(b)
	self._ui["Panel_lock"]:setVisible(b)
end

function ClassRef:setMask(b)
	self:setColor( b and display.COLOR_GRAY or display.COLOR_WHITE )
	self:setClickEnable( not b )
	if self._model then
		self._model:setUIState("mask", b)
	end
end

function ClassRef:setIsOther(b)
	self._ui["mask_red"]:setVisible(b)
end

function ClassRef:setEquiped(b)
	self._ui["equipped"]:setVisible(b)
end

-- 是否可转移
function ClassRef:setTransferred(b)
	self._ui["shift"]:setVisible(b)
end
-- 是否更强标记
function ClassRef:setStrengthen(b)
	self._ui["cue"]:setVisible(b)
end

-- 是否可继续强化
function ClassRef:setContinueStrengthen(b)
	-- self._ui["img_ContinueFlag"]:setVisible(b)
end

-- 已强化等级
function ClassRef:setStrengthenedLv( num )
	if num and num > 0 then
		self._ui["num"]:setVisible(true)
		self._ui["num"]:setString( "+" .. num )
	else
		self._ui["num"]:setVisible(false)
	end
end

-- 已强化等级
function ClassRef:setStrengthenedLvEx(num)
	if num and num > 0 then
		self._ui["num"]:setVisible(true)
		self._ui["num"]:setString(num)
	else
		self._ui["num"]:setVisible(false)
	end
end

function ClassRef:setGetReward(b)
	-- self._ui.icon_claimed:setVisible(b)
end

function ClassRef:isSelected()
	return self._ui["selected"]:isVisible()
end

function ClassRef:setSelected( b )
	self._ui["selected"]:setVisible( b )
	if self._model then
		self._model:setUIState("selected", b)
	end
end

function ClassRef:setClickEnable( b )
	if not self._data then
		b = false
	end
	self:setTouchEnabled( b )
end

function ClassRef:onBtnClick(func)
	self._onClick = func
end

--pos = {x=, y=}
function ClassRef:setTipEnable(b, pos, isTouch)
	self._tipEnable = b
	self._tipPos = pos
	self._isTouchTip = isTouch or false
	-- self:addTouchEvent()
end

function ClassRef:setCellModel(model)
	self._model = model
end



-- function ClassRef:addTouchEvent()
-- 	if self._isTouchTip then
-- 		local function touchEvent(sender, eventType)
-- 			if not self._isTouchTip then return end
-- 			if eventType == ccui.TouchEventType.began then
-- 				self._delayAct = sender:performWithDelay(function()
-- 						self._delayAct = nil

-- 						local worldPos = self._bgBtn:convertToWorldSpace(cc.p(0,0))
-- 						self._tipPos = self._tipPos or {x=2/5, y=1/2}
-- 						if worldPos.x < display.cx then
-- 							self._tipPos.x = 5/8
-- 						else
-- 							self._tipPos.x = 1/4
-- 						end
-- 						self:setSelected(true)
-- 						self:showTip()
-- 					end, 0.1)
-- 			elseif eventType == ccui.TouchEventType.canceled or eventType == ccui.TouchEventType.ended then
-- 				if self._delayAct then
-- 					sender:stopAction(self._delayAct)
-- 					self._delayAct = nil
-- 					if eventType == ccui.TouchEventType.ended then
-- 						executeFunc(self._onClick, self)
-- 					end
-- 				else
-- 					UIHandler:hideFloatPanel()
-- 					self:setSelected(false)
-- 				end
-- 				if eventType == ccui.TouchEventType.canceled then
-- 					self:setSelected(false)
-- 				end
-- 			end
-- 		end
-- 		self._bgBtn:addTouchEventListener(touchEvent)
-- 	end
-- end

function ClassRef:showTip()
	if not self._data then
		return
	end
	local renderData = self._data
	if self._tipEnable and renderData then
		local data = renderData
		local type = renderData.itemBagType

		local param = {itemId=tonumber(data.tid)}
		local tipsType
		if type == Enums.ItemBagType.equip then
			tipsType = Enums.TipsType.equip
			if not data:isFromConf() then
				param.dataTemp = data
			end
		elseif type == Enums.ItemBagType.jewel then
			tipsType = Enums.TipsType.jewel
		else
			tipsType = Enums.TipsType.item
		end

		param.tipsType = tipsType
		param.closeCallBack = function()
			-- print("BagRender.removeTip")
			if not tolua.isnull( self ) then
				self:setSelected(false)
			end
		end
		local boundingBoxTemp = self:getBoundingBox()
		local worldPosTemp = self:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
		boundingBoxTemp.x = worldPosTemp.x
		boundingBoxTemp.y = worldPosTemp.y
		param.boundingBox = boundingBoxTemp
		app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params=param})
	end
end

return ClassRef
